<?php

namespace SunAdmin\Controller;

use SunAdmin\Common\ResponseJson;
use SunAdmin\Service\TimerTaskService;
use think\swoole\Manager;

class TimerTaskController
{
    public function getTaskList()
    {
        $param = request()->param([
            'page'=>1,
            'limit'=>20
        ]);
        $res = TimerTaskService::getTaskList($param['page'], $param['limit']);
        return ResponseJson::success($res);
    }

    public function save(){
        $param = request()->param([
            'id'=>0,
            'name'=>'',
            'desc'=>'',
            'type'=>'',
            'schedule_config'=>[],
            'class_name'=>'',
            'method_name'=>'',
            'enabled'=>1,
            'log_level'=>'full'
        ]);
        TimerTaskService::save($param);
        return ResponseJson::success();
    }

    public function getTaskLogs()
    {
        $param = request()->param([
            'page'=>1,
            'limit'=>20,
            'where'=>[]
        ]);
        $res = TimerTaskService::getTaskLogs($param['where'],$param['page'],$param['limit']);
        return ResponseJson::success($res);
    }

    /**
     * 手动执行任务
     */
    public function manualExecute()
    {
        $param = request()->param([
            'id' => 0
        ]);
        $manage = app(Manager::class);
        go(function () use ($manage,$param) {
            $manage->runInSandbox(function () use ($manage,$param) {
                if (empty($param['id'])) {
                    return ResponseJson::error('任务ID不能为空');
                }
                TimerTaskService::manualExecute($param['id']);
                return true;
            });
        });
        return ResponseJson::success('任务后台执行,请关注任务日志');
    }
}